import { Component, createRef } from "react";
import { View, Button } from "@tarojs/components";
// import { AtImagePicker } from "taro-ui";
// import {Form, FormItem} from "@antmjs/vantui";
import { Uploader, Divider } from "@antmjs/vantui";
import Taro from "@tarojs/taro";
// import { isEmpty } from "lodash";
import {
  CustomizeForm,
  CustomizeFormExpose,
  FormCheckboxGroup,
  //   FormDependency,
  FormPicker,
  //   FormRadioGroup,
  //   FormSwitch,
  FormTextArea,
  FormTextInput
} from "form-taro3-react";
// import { copyrightTypeCHN } from "../../../util/copyright-type";
import "@antmjs/vantui/es/uploader/style";
import "@antmjs/vantui/es/divider/style";
// import start from "../../../static/start.png";
import "./copyright-submit.scss";

export default class CopyrightSubmit extends Component {
  // 表单 Ref
  formRef = createRef<CustomizeFormExpose>();

  state = {
    workType: [
      "文学作品",
      "口述作品",
      "音乐作品",
      "戏剧作品",
      "舞蹈作品",
      "杂技作品",
      "美术作品",
      "摄影作品",
      "工程设计图",
      "产品设计图",
      "地图",
      "示意图",
      "模型作品",
      "建筑作品",
      "拍摄独创作品",
      "电影作品",
      "汇编作品"
    ],
    creativeNature: ["原创", "改编", "翻译", "汇编", "注释", "整理", "其他"],
    rightAcquisitionMode: ["原始", "继承", "承受", "其他"],
    attributionOfWorks: [
      "个人作品",
      "合作作品",
      "法人作品",
      "职务作品",
      "委托作品"
    ],
    formData: {},
    workTypeValue: "",
    creativeNatureValue: "",
    rightAcquisitionModeValue: "",
    attributionOfWorksValue: "",
    fileList: [],
    cloudPath: [],
    specialapplications: []
  };

  /**
   * 表单校验
   */
  validate() {
    // const {attributionOfWorks,rightAcquisitionMode,creativeNature,workType} = this.state
    this.formRef.current
      ?.validate()
      .then(() => {
        if (!this.state.fileList.length) {
          Taro.showToast({ title: "请上传清晰作品图片", icon: "none" });
          return;
        }
        // 校验通过
        // 获取表单值
        console.log(this.formRef.current?.getFieldsValue());
        const {
          workName,
          content,
          ownershipOfRights
        } = this.formRef.current?.getFieldsValue();
        const data = {
          userCopyRightType: "1",
          workName,
          content,
          ownershipOfRights,
          copyrightchart: this.state.cloudPath[0].fileID,
          // specialapplications: this.state.specialapplications,
          workType: this.state.workTypeValue,
          creativeNature: this.state.creativeNatureValue,
          rightAcquisitionMode: this.state.rightAcquisitionModeValue,
          attributionOfWorks: this.state.attributionOfWorksValue
        };
        this.setState({
          formData: data
        });
        console.log("formData:", this.state.formData);
        Taro.showLoading({ title: "上传中,请稍后" }).then();
        Taro.cloud
          .callFunction({
            name: "logins",
            data: {
              $url: "addCopyRight",
              data: this.state.formData
            }
          })
          .then((res: any) => {
            if (res.result.code === 0) {
              Taro.showToast({ title: "提交成功", icon: "success" }).then(
                () => {
                  Taro.navigateTo({
                    url: "/pages/index/index"
                  }).then();
                }
              );
            }
          });
      })
      .catch(error => {
        // 校验不通过
        console.log(error);
      });
  }

  handleChange = res => {
    console.log(this.state.workType[res]);
    this.setState({
      workTypeValue: this.state.workType[res]
    });
  };

  handleChange1 = res => {
    this.setState({
      creativeNatureValue: this.state.creativeNature[res]
    });
  };

  handleChange2 = res => {
    this.setState({
      rightAcquisitionModeValue: this.state.rightAcquisitionMode[res]
    });
  };

  handleChange3 = res => {
    this.setState({
      attributionOfWorksValue: this.state.attributionOfWorks[res]
    });
  };
  

  afterRead(event: any) {
    const { file } = event.detail;
    this.uploadToCloud(file);
  }

  uploadToCloud(data: any) {
    Taro.cloud.init();
    // const { fileList } = data;
    if (!data.length) {
      Taro.showToast({ title: "请选择图片", icon: "none" });
    } else {
      const uploadTasks = data.map((file: any) => this.uploadFilePromise(file));
      Taro.showLoading({ title: "上传中" });
      Promise.all(uploadTasks)
        .then(data => {
          Taro.showToast({ title: "上传成功", icon: "none" });
          const newFileList = data.map((item: any) => ({
            url: item.fileID
          }));
          this.setState({ cloudPath: data, fileList: newFileList });
        })
        .catch(e => {
          Taro.showToast({ title: "上传失败", icon: "none" });
          console.log(e);
        });
    }
  }

  uploadFilePromise(chooseResult: any) {
    return Taro.cloud.uploadFile({
      cloudPath: new Date().getTime() + ".png",
      filePath: chooseResult.url
    });
  }

  handleDelete(event: any) {
    Taro.cloud.init();
    const { fileList, index, file } = event.detail;
    Taro.cloud
      .deleteFile({
        fileList: [file.url]
      })
      .then(res => {
        console.log(res);
        fileList.splice(index, 1);
        this.setState({ fileList });
      });
  }

  render() {
    return (
      <View className="index">
        <CustomizeForm
          ref={this.formRef}
          //   defaultValue={{ content: "请输入作品创作说明" }}
          onValueChange={diff => {
            console.log(diff);
          }}
        >
          <FormTextInput
            label="作品名称"
            fieldProps={{
              name: "workName",
              placeholder: "请输入作品名称"
            }}
            rules={{ required: true, message: "作品名称不能为空" }}
          />
          <FormPicker
            label="作品类型"
            onPickerChange={this.handleChange.bind(this)}
            fieldProps={{
              name: "workType",
              mode: "selector",
              range: this.state.workType
            }}
            rules={{ required: true, message: "作品类型不能为空" }}
          />
          <FormPicker
            label="作品创作性质"
            onPickerChange={this.handleChange1.bind(this)}
            fieldProps={{
              name: "creativeNature",
              mode: "selector",
              range: this.state.creativeNature
            }}
            rules={{ required: true, message: "作品创作性质不能为空" }}
          />
          <FormPicker
            label="权利取得方式"
            onPickerChange={this.handleChange2.bind(this)}
            fieldProps={{
              name: "rightAcquisitionMode",
              mode: "selector",
              range: this.state.rightAcquisitionMode
            }}
            rules={{ required: true, message: "权利取得方式不能为空" }}
          />
          <FormPicker
            label="作品归属"
            onPickerChange={this.handleChange3.bind(this)}
            fieldProps={{
              name: "attributionOfWorks",
              mode: "selector",
              range: this.state.attributionOfWorks
            }}
            rules={{ required: true, message: "作品归属不能为空" }}
          />
          {/* <FormRadioGroup
            label="性别"
            fieldProps={{
              name: "selector"
            }}
            options={[
              { label: "男", option: { value: "1" } },
              { label: "女", option: { value: "2" } }
            ]}
            rules={{ required: true, message: "请选择" }}
          /> */}
          <FormTextArea
            label="作品创作说明"
            fieldProps={{ name: "content", placeholder: "请输入作品创作说明" }}
            rules={{ required: true, message: "作品创作说明不能为空" }}
          />
          {/* <FormDependency
            renderer={form => {
              return form?.selector === "1" ? (
                <Text>你选择了：男</Text>
              ) : (
                <Text>你选择了：女</Text>
              );
            }}
          /> */}
          {/* <FormSwitch
            label="开关"
            fieldProps={{ name: "switch" }}
            rules={{ required: true, message: "请选择开关" }}
          /> */}
          <FormCheckboxGroup
            label="权利拥有方式"
            fieldProps={{
              name: "ownershipOfRights"
            }}
            options={[
              { label: "发表权", value: "FB" },
              { label: "署名权", value: "SM" },
              { label: "修改权", value: "XG" },
              { label: "保护作品完整权", value: "BHZPWZ" },
              { label: "复制权", value: "FZ" },
              { label: "发行权", value: "FX" },
              { label: "出租权", value: "CZ" },
              { label: "展览权", value: "ZL" },
              { label: "表演权", value: "BY" },
              { label: "放映权", value: "FYIN" },
              { label: "广播权", value: "GBO" },
              { label: "信息网络传播权", value: "XXWLCB" },
              { label: "摄影权", value: "SY" },
              { label: "改编权", value: "GB" },
              { label: "翻译权", value: "FYI" },
              { label: "汇编权", value: "HB" },
              { label: "其他", value: "QT" }
            ]}
            rules={{ required: true, message: "权利拥有方式不能为空" }}
          />

          <View>
            <Divider />
            <View style={{ marginBottom: "10px" }}>清晰的作品样本(点击图片可以放大预览)</View>
            <Uploader
              fileList={this.state.fileList}
              onAfterRead={this.afterRead.bind(this)}
              multiple
              onDelete={this.handleDelete.bind(this)}
              maxCount={1}
            />
          </View>

          <Button className="btn" onClick={this.validate.bind(this)}>
            提交申请
          </Button>
        </CustomizeForm>
      </View>
    );
  }
}
